package com.ricchieri.manage.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.springframework.dao.DataAccessException;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.model.User;
import com.ricchieri.util.FacesUtil;

@ManagedBean(name = "addUserMB")
@ViewScoped
public class AddUserManageBean extends CommonUserManageBean {

	private static final long serialVersionUID = -4587184672374145123L;
	
	public String save() {
		try {
			
			if(validateForm()) {
				this.setDefaultEmail();
				this.setDefaultPhone();
				getUser().setAutorized(Boolean.TRUE);
				getUser().setDocumentType(this.obtainDocumentType(getDocumentType()));
				getUser().setUserEmail(this.getEmails());
				getUser().setUserPhone(this.getPhones());
				
				getUser().setRoles(this.generateRoles(getUser()));
				
				getUserService().addUser(getUser());
				FacesUtil.addParametersFlash(BusinessSettings.KEY_USER, getUser());
				return BusinessSettings.SUCCESS;
			} else {
				return BusinessSettings.UNSUCCESS;
			}
			
		} catch (DataAccessException e) {
			return BusinessSettings.UNSUCCESS;
		}
	}
			
	public void reset() {
		setPhone(null);
		setNumber(null);
		setEmailType(null);
		setEmail(null);
		setDocumentType(null);
		setUser(new User());
		setEmails(null);
		setPhones(null);
		setSelectedUserEmail(null);
		setSelectedUserPhone(null);
		setEmailDataModel(null);
		setPhoneDataModel(null);
		this.modifyEmailsTypes();
		this.modifyPhonesTypes();
	}

	@Override
	protected String getFormName() {
		return "addUserForm";
	}

	@Override
	public Boolean isRequeriedUser() {
		return Boolean.FALSE;
	}
}

